package net.pws.oos.biz.service.impl;

import java.util.Date;
import java.util.Set;

import net.pws.common.event.ApplicationEventBus;
import net.pws.common.persistence.EntityManager;
import net.pws.common.persistence.UnitOfWork;
import net.pws.oos.biz.event.NoticeCreatedEventObject;
import net.pws.oos.biz.event.NoticeReadEventObject;
import net.pws.oos.biz.model.Notice;
import net.pws.oos.biz.model.NoticeReceiver;
import net.pws.oos.biz.model.User;
import net.pws.oos.biz.query.NoticeFinder;
import net.pws.oos.biz.service.NoticeService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class DefaultNoticeService implements NoticeService {
    
    @Autowired
    private EntityManager entityManager;
    
    @Autowired
    private NoticeFinder noticeFinder;
    
    public Notice create(Notice notice, Set<User> users) {
        // entityManager.persist(notice);
        UnitOfWork unitOfWork = new UnitOfWork();
        unitOfWork.registerNew(notice);
        for (User user : users) {
            NoticeReceiver noticeReceiver = new NoticeReceiver();
            noticeReceiver.setNotice(notice);
            noticeReceiver.setReceiver(user);
            unitOfWork.registerNew(noticeReceiver);
        }
        entityManager.execute(unitOfWork);
        
        // 发送事件
        NoticeCreatedEventObject event = new NoticeCreatedEventObject(notice,
                                                                      users);
        ApplicationEventBus.getInstance().publishEvent(event);
        
        return notice;
    }
    
    public void delete(String noticeId) {
        Notice notice = entityManager.find(Notice.class, noticeId);
        if (notice != null) {
            notice.setDeleted(Boolean.TRUE);
            entityManager.persist(notice);
        }
    }
    
    public void read(String noticeId, String userId) {
        NoticeReceiver receiver = noticeFinder.findReceiver(noticeId, userId);
        if (receiver != null && receiver.getReadDate() == null) {
            receiver.setReadDate(new Date());
            entityManager.persist(receiver);
            
            // 发送事件
            NoticeReadEventObject event = new NoticeReadEventObject(noticeId,
                                                                    userId);
            ApplicationEventBus.getInstance().publishEvent(event);
        }
    }
    
}
